package com.fyzk.activity.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ahwf.dialog.BottomDialog;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.chongzhi.RechargeActivity;
import com.fyzk.activity.dialog.AppDialog;
import com.fyzk.activity.lottery.shuzicai.InfoDetailActivity;
import com.fyzk.activity.lottery.shuzicai.WebViewActivity;
import com.fyzk.activity.setting.SettingActivity;
import com.fyzk.activity.share.ShareCodeActivity;
import com.fyzk.activity.share.ShareTuijianActivity;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.activity.user.UserCenterTogetherBuyActivity;
import com.fyzk.activity.user.UserCenterZhuihaoActivity;
import com.fyzk.activity.user.WithdrawActivity;
import com.fyzk.activity.user.accountdetail.AccountStatementActivity;
import com.fyzk.activity.user.coupon.CouponActivity;
import com.fyzk.activity.user.touzhu.CommonBetActivity;
import com.fyzk.activity.user.userinfo.AuthenticationActivity;
import com.fyzk.activity.user.userinfo.ChangePasswordActivity;
import com.fyzk.activity.user.userinfo.PersonalInformationActivityNew;
import com.fyzk.base.BaseFragment;
import com.fyzk.bean.AccountMoneyResponse;
import com.fyzk.bean.RechargeBean;
import com.fyzk.bean.UserInfoResponse;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.OfflineDialog;
import com.fyzk.dialog.PublicDialog;
import com.fyzk.dialog.WxCodeDialog;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.FileUtils;
import com.fyzk.utils.ImageUtils;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtils;
import com.fyzk.utils.Utils;
import com.fyzk.utils.update.CustomerCalls;
import com.fyzk.utils.update.VersionModel;
import com.fyzk.view.MyScrollView;
import com.fyzk.view.OnRefreshListener;
import com.fyzk.view.PullToRefreshLayout;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.BuildConfig;
import com.tyjc.lottery.R;
import com.wf.domain.UrlDef;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.io.File;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

import static android.app.Activity.RESULT_OK;

/**
 * <p>
 *
 * @author
 * @mood
 * @description
 * @date 2019/8/30 11:39
 * </p>
 */
public class PersonalFragment extends BaseFragment implements View.OnClickListener,
        OnRefreshListener, BottomDialog.OnEntryClickListener {

    private PullToRefreshLayout mRefreshLayout;
    private MyScrollView mScrollview;
    private ImageView ivPhoto;
    private TextView tvUsername;
    private ImageButton btnSetting;
    private TextView tvAllowUse;
    private TextView tvRecharge;
    private RelativeLayout tvRechargeRl;
    private TextView tvZhuancun;
    private RelativeLayout tvZhuancunRl;
    private TextView tvAllowWithdraw;
    private TextView tvWithdraw;
    private RelativeLayout tvWithdrawRl;
    private TextView tvAction1;
    private TextView tvAction2;
    private TextView tvAction3;
    private TextView tvAction4;
    private TextView tvAction5;
    private TextView tvAction6;
    private TextView tvAction7;
    private TextView tvAction8;
    private TextView tvAction9;
    private TextView tvAction12;
    private TextView tvAction10;

    private TextView tuijian100;

    private String[] mHeadSourceData = new String[]{"我的相册", "拍照"};
    private static final int REQUEST_CODE_PHOTO = 0x1;
    private static final int REQUEST_CODE_CAMERA = 0x2;
    private static final int REQUEST_CODE_CROP = 0x3;
    private Bitmap mBitmap;

    boolean isLogin = false;

    private MySharedPreferences mySharedPreferences;
    //客服电话
//    private String servicePhone = "";
    //客服QQ
//    private String serviceQQ = "";

    private AccountMoneyResponse accountMoneyResponse;
    private UserInfoResponse userInfoResponse;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mainView = inflater.inflate(R.layout.personal_layout_new, null);
        return mainView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initEvent();
        initData();
        CustomerCalls customerCalls = MySharedPreferences.getInstance().getCustomerCalls();
        if (customerCalls != null && !TextUtils.isEmpty(customerCalls.getChatUrl())) {
            if (tvAction9 != null) {
                tvAction9.setVisibility(View.VISIBLE);
            }
        } else {
            if (tvAction9 != null) {
                tvAction9.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        CustomerCalls customerCalls = MySharedPreferences.getInstance().getCustomerCalls();
        if (customerCalls != null && !TextUtils.isEmpty(customerCalls.getChatUrl())) {
            if (tvAction9 != null) {
                tvAction9.setVisibility(View.VISIBLE);
            }
        } else {
            if (tvAction9 != null) {
                tvAction9.setVisibility(View.GONE);
            }
        }
    }

    private void initView(View view) {

        Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "fonts/pingfang.ttf");

        mRefreshLayout = view.findViewById(R.id.userCenterFrag_refreshLayout);
        mScrollview = view.findViewById(R.id.userCenterFrag_scrollview);

        ivPhoto = view.findViewById(R.id.userCenterFrag_ivPhoto);
        tvUsername = view.findViewById(R.id.userCenterFrag_tvUsername);
        tvUsername.setTypeface(tf);
        btnSetting = view.findViewById(R.id.userCenterFrag_btnSetting);
        tvAllowUse = view.findViewById(R.id.userCenterFrag_tvAllowUse);
        tvAllowUse.setTypeface(tf);
        tvRecharge = view.findViewById(R.id.userCenterFrag_tvRecharge);
        tvRechargeRl = view.findViewById(R.id.userCenterFrag_tvRecharge_rl);
        tvZhuancun = view.findViewById(R.id.userCenterFrag_tvZhuancun);
        tvZhuancunRl = view.findViewById(R.id.userCenterFrag_tvZhuancun_rl);
        tvZhuancun.setTypeface(tf);
        tvRecharge.setTypeface(tf);
        tvAllowWithdraw = view.findViewById(R.id.userCenterFrag_tvAllowWithdraw);
        tvAllowWithdraw.setTypeface(tf);
        tvWithdraw = view.findViewById(R.id.userCenterFrag_tvWithdraw);
        tvWithdrawRl = view.findViewById(R.id.userCenterFrag_tvWithdraw_rl);
        tvWithdraw.setTypeface(tf);
        tvAction1 = view.findViewById(R.id.userCenterFrag_tvAction1);
        tvAction1.setTypeface(tf);
        tvAction2 = view.findViewById(R.id.userCenterFrag_tvAction2);
        tvAction2.setTypeface(tf);
        tvAction3 = view.findViewById(R.id.userCenterFrag_tvAction3);
        tvAction3.setTypeface(tf);
        tvAction4 = view.findViewById(R.id.userCenterFrag_tvAction4);
        tvAction4.setTypeface(tf);
        tvAction5 = view.findViewById(R.id.userCenterFrag_tvAction5);
        tvAction5.setTypeface(tf);
        tvAction6 = view.findViewById(R.id.userCenterFrag_tvAction6);
        tvAction6.setTypeface(tf);
        tvAction7 = view.findViewById(R.id.userCenterFrag_tvAction7);
        tvAction7.setTypeface(tf);
        tvAction8 = view.findViewById(R.id.userCenterFrag_tvAction8);
        tvAction8.setTypeface(tf);
        tvAction9 = view.findViewById(R.id.userCenterFrag_tvAction9);
        tvAction9.setTypeface(tf);
        tvAction12 = view.findViewById(R.id.userCenterFrag_tvAction12);
        tvAction12.setTypeface(tf);
        tvAction10 = view.findViewById(R.id.userCenterFrag_tvAction10);
        tvAction10.setTypeface(tf);
        tuijian100 = view.findViewById(R.id.tuijian100);
        tuijian100.setTypeface(tf);
    }


    private void initEvent() {
        mRefreshLayout.setOnRefreshListener(this);
        ivPhoto.setOnClickListener(this);
        tvUsername.setOnClickListener(this);
        btnSetting.setOnClickListener(this);
        tvRechargeRl.setOnClickListener(this);
        tvWithdrawRl.setOnClickListener(this);
        tvZhuancunRl.setOnClickListener(this);
        tvAction1.setOnClickListener(this);
        tvAction2.setOnClickListener(this);
        tvAction3.setOnClickListener(this);
        tvAction4.setOnClickListener(this);
        tvAction5.setOnClickListener(this);
        tvAction6.setOnClickListener(this);
        tvAction7.setOnClickListener(this);
        tvAction8.setOnClickListener(this);
        tvAction9.setOnClickListener(this);
        tvAction12.setOnClickListener(this);
        tvAction10.setOnClickListener(this);
        tuijian100.setOnClickListener(this);
        mScrollview.setOnScrollChanged(new MyScrollView.OnScrollChanged() {
            @Override
            public void onScroll(ScrollView view, int l, int t, int oldl, int oldt) {
                mRefreshLayout.setCanPull(view.getScrollY() == 0);
            }
        });
    }

    private void initData() {
        mySharedPreferences = MySharedPreferences.getInstance();
//        serviceQQ = mySharedPreferences.getServiceQQ();
//        servicePhone = mySharedPreferences.getCustomerCalls();
    }

    private void requestLeftMoney() {
        httpPostJson(CommandUtil.ACCOUNT_MONEY, Commands.ACCOUNT_MONEY, null, true);
    }

    //查询用户信息
    private void requestUserInfo() {
        httpPostJson(CommandUtil.USERINFO, Commands.USERINFO, null, false);
    }

    private void updateUserViews() {
        if (mySharedPreferences.getAlias().equals("")) {
            tvUsername.setText(mySharedPreferences.getUserName());
        } else {
            tvUsername.setText(mySharedPreferences.getAlias());
        }

        String photoUrl = mySharedPreferences.getPhotoUrl();
        if (!TextUtil.isEmpty(photoUrl)) {
            Glide.with(getContext()).load(photoUrl)
                    .error(R.drawable.header)
                    .into(ivPhoto);
        }

        tvAllowUse.setText(Utils.getPrice(mySharedPreferences.getBalance()));
        tvAllowWithdraw.setText(Utils.getPrice(mySharedPreferences.getDrawbalance()));
    }

    private void unLoginViews() {
        tvUsername.setText("去登录/注册");
        tvAllowUse.setText("");
        tvAllowWithdraw.setText("");
        ivPhoto.setImageResource(R.drawable.header);
    }

    @Override
    public void onResume() {
        super.onResume();
        isLogin = mySharedPreferences.getLoginStatus();
        if (!isLogin) {
            tvUsername.setText("去登录/注册");
            tvAllowUse.setText("");
            tvAllowWithdraw.setText("");
        } else {
            updateUserViews();
            requestLeftMoney();
            requestUserInfo();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.ACCOUNT_MONEY:
                mRefreshLayout.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
                accountMoneyResponse = JSON.parseObject(resultBean.getData(),
                        AccountMoneyResponse.class);

                mySharedPreferences.setBalance(PublicMethod
                        .formatBalance(accountMoneyResponse
                                .getBalance()));
                mySharedPreferences.setDrawbalance(PublicMethod
                        .formatBalance(accountMoneyResponse
                                .getDrawbalance()));
                mySharedPreferences.setFreeze(PublicMethod
                        .formatBalance(accountMoneyResponse
                                .getFreeze()));
                tvAllowUse.setText(Utils.getPrice(mySharedPreferences.getBalance()));
                tvAllowWithdraw.setText(Utils.getPrice(mySharedPreferences.getDrawbalance()));

                break;
            case CommandUtil.USERINFO:
                userInfoResponse = JSON.parseObject(resultBean.getData(), UserInfoResponse.class);
                break;
            case CommandUtil.UPDATEHEAD:
                showToast("上传成功");
                String headUrl = resultBean.getData();
                LogUtils.e("====headUrl====" + headUrl);
                if (headUrl != null) {
                    mySharedPreferences.setPhotoUrl(headUrl);
                    Glide.with(getContext()).load(headUrl)
                            .error(R.drawable.header)
                            .into(ivPhoto);
                }
                break;
            case CommandUtil.RECHARGE:
                // 新充值渠道接口返回
                RechargeBean rechargeBean = JSON.parseObject(resultBean.getData(), RechargeBean.class);
                //线下充值
                showOfflineDialog(rechargeBean);
                break;
            case CommandUtil.CONTACT:

                LogUtils.e("====CONTACT result====" + result);

                VersionModel beans = JSON.parseObject(resultBean.getData(), VersionModel.class);
//                UpdateManager.getUpdateManager().getVersion(getActivity(), beans, "0");

                if (beans != null) {
                    if (!TextUtils.isEmpty(beans.getQr_url())) {
                        MySharedPreferences.getInstance().setQrUrl(beans.getQr_url());
                    }

                    if (!TextUtils.isEmpty(beans.getHandsel_content())) {
                        MySharedPreferences.getInstance().setHandselContent(beans.getHandsel_content());
                    }

                    VersionModel.Version model = beans.getVersion();
//                    if (model != null && !TextUtils.isEmpty(model.getContent())) {
//                        homeFragment.setNoticeText(model.getContent());
//                    }

                    if (model != null && !TextUtils.isEmpty(model.getCustomercalls())) {
                        MySharedPreferences.getInstance().setCustomerCalls(model.getCustomercalls());
                    }

                    if (model != null && !TextUtils.isEmpty(model.getQQ())) {
                        MySharedPreferences.getInstance().setServiceQQ(model.getQQ());
                    }

                    if (model != null && !TextUtils.isEmpty(model.getDrawContent())) {
                        MySharedPreferences.getInstance().setDrawContent(model.getDrawContent().replaceAll("\\\\n", "\n"));
                    }

                    String splashImageUrl = MySharedPreferences.getInstance().getSplashImageUrl();
                    if (model != null && !TextUtils.isEmpty(model.getImage_url()) && !splashImageUrl.equals(model.getImage_url())) {
                        MySharedPreferences.getInstance().setSplashImageUrl(model.getImage_url());
                    }
                    //客服微信图片暂时用跟启动图一样的
                    String qqImageUrl = MySharedPreferences.getInstance().getQQImageUrl();
                    if (model != null && !TextUtils.isEmpty(model.getImage_url()) && !qqImageUrl.equals(model.getImage_url())) {
                        MySharedPreferences.getInstance().setQQImageUrl(model.getImage_url());
                    }
                    if (!TextUtil.isEmpty(MySharedPreferences.getInstance().getServiceQQ()))
                        showContactDialog();
                }
                break;
        }
    }

    private void showOfflineDialog(RechargeBean rechargeBean) {
        WxCodeDialog mDialog = new WxCodeDialog(getActivity(), rechargeBean, "");
        mDialog.show();
    }

    @Override
    public void onFailure(int requestCode, String errorcode, String msg) {
        if (errorcode.equals("110003")) {
            unLoginViews();
            mySharedPreferences.setLoginStatus(false);
            mRefreshLayout.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
        }
    }

    @Override
    protected void onFailure(int requestCode, String message) {
        switch (requestCode) {
            case CommandUtil.ACCOUNT_MONEY:
                mRefreshLayout.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
                break;
            default:
                super.onFailure(requestCode, message);
                break;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_PHOTO://本地相册获取
                if (resultCode == RESULT_OK) {
                    shearPhoto(data.getData()); // 剪切图片
                }
                break;
            case REQUEST_CODE_CAMERA://相机获取
                if (resultCode == RESULT_OK) {
                    File fileTemp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                    Uri photoURI = FileUtils.getUriForFile(getActivity(), fileTemp);
                    shearPhoto(photoURI); // 剪切图片
                }
                break;
            case REQUEST_CODE_CROP:
                if (data != null) {
                    mBitmap = data.getParcelableExtra("data");
                    if (mBitmap != null) {
                        ivPhoto.setImageBitmap(mBitmap);
                        httpUpLoadHeadPic(mBitmap);
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 上传头像接口
     */
    private void httpUpLoadHeadPic(Bitmap mBitmap) {
        ImageUtils.saveImageToSD(mBitmap, 0, getContext());
        String imagePath = ImageUtils.getSavePathName(0);
        File file = new File(imagePath);

        RequestParams params = new RequestParams(UrlDef.HEDA_URL);
        // 使用multipart表单上传文件
        params.setMultipart(true);
        if (file.exists()) {
            params.addBodyParameter("file", file, "image/png");
            params.addBodyParameter("type", "1"); //1用户头像，2晒单图片
            params.addBodyParameter("userno", accountMoneyResponse.getUserno());
        }

        LogUtils.e("====params====" + params.toString());
        httpPostJsonHead(CommandUtil.UPDATEHEAD, params, true);
    }


    @Override
    public void onClick(View v) {
        if (!isLogin) {
            actionLogout();
            return;
        }

        switch (v.getId()) {
            case R.id.userCenterFrag_ivPhoto:
                showBottomDialog();
                break;
            case R.id.userCenterFrag_tvUsername:
                if (!MySharedPreferences.getInstance().getLoginStatus()) {
                    AppLotteryInfos.clear();
                    ViewCallBack.getInstance().countDownObjs.clear();
                    ActivityTaskManager.getInstance().closeAllActivity();
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            case R.id.userCenterFrag_btnSetting:
                startActivity(new Intent(getContext(), SettingActivity.class));
                break;
            case R.id.userCenterFrag_tvRecharge_rl:
                startActivity(new Intent(getContext(), RechargeActivity.class));
                break;
            case R.id.userCenterFrag_tvZhuancun_rl:
                withdraw(1);
                break;
            case R.id.userCenterFrag_tvWithdraw_rl:
                withdraw(0);
                break;
            case R.id.userCenterFrag_tvAction1:
                startActivity(new Intent(getContext(), CommonBetActivity.class));
                break;
            case R.id.userCenterFrag_tvAction2:
                startActivity(new Intent(getContext(), UserCenterZhuihaoActivity.class));
                break;
            case R.id.userCenterFrag_tvAction3:
                startActivity(new Intent(getContext(), UserCenterTogetherBuyActivity.class));
                break;
            case R.id.userCenterFrag_tvAction4:
                startActivity(new Intent(getActivity(), CouponActivity.class));
                break;
            case R.id.userCenterFrag_tvAction5:
                startActivity(new Intent(getActivity(), ShareTuijianActivity.class));
                break;
            case R.id.tuijian100:
                startActivity(new Intent(getActivity(), ShareCodeActivity.class));
//                Intent intent1=new Intent(Intent.ACTION_VIEW);
//                intent1.setData(Uri.parse("http://vip.cqssc28.com:8008/invite?userno="+MySharedPreferences.getInstance().getUserNo()));
//                startActivity(intent1);
                break;
            case R.id.userCenterFrag_tvAction6:
                startActivity(new Intent(getContext(), AccountStatementActivity.class));
                break;
            case R.id.userCenterFrag_tvAction7:
                startActivity(new Intent(getContext(), PersonalInformationActivityNew.class));
                break;
            case R.id.userCenterFrag_tvAction8:
                Intent intent = new Intent(getContext(), ChangePasswordActivity.class);
                intent.putExtra(IntentParamUtils.USERNAME, tvUsername.getText());
                startActivity(intent);
                break;
            case R.id.userCenterFrag_tvAction9:
//                showWxDialog(serviceQQ);
//                rechargeOffLine();
//                showContactDialog();
                jumpChatService();
                break;
            case R.id.userCenterFrag_tvAction12:
//                showWxDialog(serviceQQ);
//                rechargeOffLine();
                showContactDialog();
                break;
//            case R.id.userCenterFrag_tvAction10:
//                call(servicePhone);
//                break;
        }
    }

    /**
     * 跳转联系客服
     */
    private void jumpChatService() {
        CustomerCalls customerCalls = MySharedPreferences.getInstance().getCustomerCalls();
        String url = "";
        if (customerCalls != null && !TextUtils.isEmpty(customerCalls.getChatUrl())) {
            url = customerCalls.getChatUrl();
        }
        if (TextUtil.isEmpty(url)) return;
        Intent intent1 = new Intent(getContext(), WebViewActivity.class);
        intent1.putExtra(IntentParamUtils.TITLE, tvAction9.getText());
        intent1.putExtra(IntentParamUtils.URL, url);
        startActivity(intent1);
    }

    public void actionLogout() {
        AppLotteryInfos.clear();
        ViewCallBack.getInstance().countDownObjs.clear();
        ActivityTaskManager.getInstance().closeAllActivity();
        MySharedPreferences.getInstance().setLoginStatus(false);
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }

    /**
     * 显示联系客服弹窗
     */
    private void showContactDialog() {
        String serviceQQ = MySharedPreferences.getInstance().getServiceQQ();
        String qqImageUrl = MySharedPreferences.getInstance().getQQImageUrl();
        if (TextUtil.isEmpty(serviceQQ)) {
            getContactByUrl();
            return;
        }
        RechargeBean bean = new RechargeBean();
        bean.setWx(serviceQQ);
        bean.setImage(qqImageUrl);
        showOfflineDialog(bean);
    }

    /**
     * 版本更新接口
     */
    private void getContactByUrl() {
        String url = UrlDef.UPDATE_URL + BuildConfig.UPDATE_KEY;
        JSONObject request_json = new JSONObject();
        try {
            httpPostJsonNo(CommandUtil.CONTACT, "", request_json, false, url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //线下充值
    private void rechargeOffLine() {
        try {
            JSONObject params = new JSONObject();
            params.put("amount", 100);
            params.put("payChannel", "wf");
            params.put("cardType", "offline");
            params.put("orderId", "HM");
            httpPostJson(CommandUtil.RECHARGE, Commands.USERPAY, params, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void showWxDialog(String wx) {
        PublicDialog mDialog = new PublicDialog(getContext(), new PublicDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
            }
        });
        mDialog.setTitle("请添加客服微信：" + wx + " 咨询");
        mDialog.setNegativeButton("取消");
        mDialog.setPositiveButton("确定");
        mDialog.show();
    }


    /**
     * 联系客服
     */
    public void connectCustomer(String qq) {
        try {
            String customerUrl = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(customerUrl)));
        } catch (Exception e) {
            e.printStackTrace();
            showToast("请先安装QQ应用");
        }
    }

    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void withdraw(int type) {
        if (userInfoResponse != null && !userInfoResponse.getRealName().equals("") &&
                !userInfoResponse.getIdcard().equals("")) {
            Intent intent = new Intent(getContext(), WithdrawActivity.class);
            intent.putExtra(IntentParamUtils.USERNAME, tvUsername.getText());
            intent.putExtra(IntentParamUtils.REALNAME, userInfoResponse.getRealName());
            intent.putExtra(IntentParamUtils.TYPE_GUOGUAN, type);
            startActivity(intent);
        } else if (userInfoResponse == null) {
            requestUserInfo();
        } else {
            AppDialog.getDialog().showPerfectInforDialog(getContext(), new AppDialog.OnAppDialogClickListener() {
                @Override
                public void onSureClick() {
                    Intent intent2 = new Intent(getContext(), AuthenticationActivity.class);
                    intent2.putExtra("userinfo", userInfoResponse);
                    startActivity(intent2);
                }

                @Override
                public void onCancleClick() {
                }
            });
        }
    }

    @Override
    public void onRefresh() {
        if (!AppUtil.isNetworkAvailable(getActivity())) {
            AppToast.getToast().show("网络已断开，请检查网络设置！");
            mRefreshLayout.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
            return;
        }
        if (!isLogin) {
            AppToast.getToast().show("尚未登录，请登录");
            mRefreshLayout.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
            tvUsername.setText("去登录/注册");
            tvAllowUse.setText("");
            tvAllowWithdraw.setText("");
        } else {
            requestLeftMoney();
        }
    }

    private void showBottomDialog() {
        //若没有授权，会弹出一个对话框（这个对话框是系统的，开发者不能自己定制），用户选择是否授权应用使用系统权限
        BottomDialog mDialog = BottomDialog.newInstance(mHeadSourceData);
        mDialog.show(getChildFragmentManager(), "dialog");
        mDialog.setOnEntryClickListener(this);
    }

    @Override
    public void onEntryClick(int position, String type) {
        if (position == 0) {
            Intent intent_photo = new Intent(Intent.ACTION_PICK, null);
            intent_photo.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent_photo, REQUEST_CODE_PHOTO);
        } else if (position == 1) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File fileTemp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtils.getUriForFile(getActivity(), fileTemp));
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
            }
        }
    }

    private void shearPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CODE_CROP);
    }
}
